<template>
  <div>
    <!-- :show-file-list="false" -->
    <el-upload
      class="avatar-uploader"
      :class="{disabled : fileList.length>0}"
      action=""
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      list-type="picture-card"
      :on-preview="handlePictureCardPreiew"
      :on-remove="handleRomove"
      :file-list="fileList"
      :limit="1"
      :http-request="onUpload"
      :on-change="onChange"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-progress v-show="showPercentage" :percentage="percentage" style="width: 198px;" />
    <el-dialog title="图片预览" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDVr8GGnD0c2FICuOdiaS7Xt53mQiohLmz',
  SecretKey: '1g8TdZLwMYXM1VnxwsiOtEPOAvSnvsdA'
})
export default {
  name: 'UploadImage',
  data() {
    return {
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: '',
      percentage: 0,
      showPercentage: false
    }
  },
  methods: {
    onChange(file) {
      this.fileList.push({ url: file.url })
    },
    onUpload({ file }) {
      this.showPercentage = true
      cos.uploadFile({
        Bucket: 'rzzt-1314095525', /* 填写自己的bucket，必须字段 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: new Date() + file.name, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: function(progressData) {
          console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        this.showPercentage = false
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功', data)
          this.fileList[0].url = `http://${data.Location}`
        }
      })
    },

    handlePictureCardPreiew(file) {
      console.log(1)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRomove() {
      this.fileList = []
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .avatar-uploader.disabled .el-upload--picture-card {
  display: none;
}
</style>
